package com.example.springboot.service;

import cn.hutool.db.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.utils.ToKenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.print.Pageable;
import java.util.List;

/**
 * 功能：接口实现类
 * 作者：陈雷
 * 日期：2024/10/18 17:30
 */

@Service
public class UserService {


    @Autowired
    UserMapper userMapper;

    //    添加用户信息
    public void insertUser(User user) {
        userMapper.insert(user);
    }

    //    修改用户信息
    public void updateUser(User user) {
        userMapper.update(user);
    }

    //    删除用户信息
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

    //    批量删除用户信息
    public void batchdeleteUser(List<Integer> ids) {
        userMapper.batchdeleteUser(ids);
    }

    //    查询全部用户信息
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    //    按id查询用户
    public User selectByid(Integer id) {
        return userMapper.selectById(id);
    }

    //登录 验证用户信息是否合法
    public User login(User user) {
        User dbuser = userMapper.selectByUsername(user.getUsername());
        if (dbuser == null) {
            // 抛出一个自定义异常
            throw new ServiceException("用户名或密码错误");
        }
        if (!dbuser.getPassword().equals(user.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }

        Integer banned = dbuser.getBanned();
        if (banned != null && banned == 1) {
            throw new ServiceException("用户被封禁");
        }

        // 生成token
        String token = ToKenUtils.createToken(dbuser.getId().toString(), dbuser.getPassword());
        dbuser.setToken(token);
        return dbuser;
    }


    //注册
    public User reqister(User user) {
        User dbuser = userMapper.selectByUsername(user.getUsername());
        if (dbuser != null){
//            抛出一个自定义异常
            throw new ServiceException("用户名已存在");
        }
        userMapper.insert(user);
        return user;
    }


    //    重置密码
    public void resetPassword(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null){
            //抛出一个自定义异常
            throw new ServiceException("用户不存在");
        }
        if (!dbUser.getPhone().equals(user.getPhone())){
            throw new ServiceException("验证错误");
        }
        //重置密码为123
        dbUser.setPassword("123");
        userMapper.update(dbUser);
    }


//    封禁用户
public void banned(String username) {
        userMapper.banned(username);
}

//    解封用户
    public void unbanned(String username) {
        userMapper.unbanned(username);
    }
}